import React from "react";
import PropTypes from "prop-types";
import { useDebouncedCallback } from "use-debounce";
import { Section, Input, InputNumber, ContextHelp } from "@/components/visualizations/editor";
import { createNumberFormatter } from "@/lib/value-format";
import * as Grid from "antd/lib/grid";

function Editor({ column, onChange }) {
  const [onChangeDebounced] = useDebouncedCallback(onChange, 200);

  return ( 
    <Section>
      <Grid.Row gutter={15} type="flex" align="middle">
        <Grid.Col span={6}>
          <Input
            label={
              <React.Fragment>
                默认值
                <ContextHelp.FunctionFormatSpecs />
              </React.Fragment>
            }
            defaultValue={column.defaultValue}
            onChange={event => onChange({ defaultValue: event.target.value })}
          />
        </Grid.Col>
        <Grid.Col span={6}>
          <Input
            label="最小值"
            defaultValue={column.minValue}
            onChange={event => onChange({ minValue: event.target.value })}
          />
        </Grid.Col>
        <Grid.Col span={6}>
          <Input
            label="最大值"
            defaultValue={column.maxValue}
            onChange={event => onChange({ maxValue: event.target.value })}
          />
        </Grid.Col>
        <Grid.Col span={6}>
          <InputNumber
            label="小数位"
            min="0"
            max="6"
            defaultValue={column.decimal || 0}
            onChange={event => onChange({ decimal: event.target.value })}
          />
        </Grid.Col>
      </Grid.Row>
    </Section>
  );
}

Editor.propTypes = {
  column: PropTypes.shape({
    name: PropTypes.string.isRequired,
    numberFormat: PropTypes.string,
  }).isRequired,
  onChange: PropTypes.func.isRequired,
};

export default function initNumberColumn(column) {
  const format = createNumberFormatter(column.numberFormat);

  function prepareData(row) {
    return {
      text: format(row[column.name]),
    };
  }

  function NumberColumn({ row }) {
    // eslint-disable-line react/prop-types
    const { text } = prepareData(row);
    return text;
  }

  NumberColumn.prepareData = prepareData;

  return NumberColumn;
}

initNumberColumn.friendlyName = "数字";
initNumberColumn.Editor = Editor;
